/**
 * (created at 2011-1-23)
 */
package qiushuo.mysqlparser.ast.expression.primary.function.groupby;

import java.util.List;

import qiushuo.mysqlparser.ast.expression.Expression;
import qiushuo.mysqlparser.ast.expression.primary.function.FunctionExpression;
import qiushuo.mysqlparser.generator.SQLType;

/**
 * @author <a href="mailto:QiuShuo1985@gmail.com">QIU Shuo</a>
 */
public class Count extends FunctionExpression {
    /**
     * either {@link distinct} or {@link wildcard} is false. if both are false,
     * expressionList must be size 1
     */
    private final boolean distinct;
    private final boolean wildcard;

    public Count(List<Expression> arguments) {
        super("COUNT", arguments);
        this.distinct = true;
        this.wildcard = false;
    }

    public Count(Expression arg) {
        super("COUNT", wrapList(arg));
        this.distinct = false;
        this.wildcard = false;
    }

    public Count() {
        super("COUNT", null);
        this.distinct = false;
        this.wildcard = true;
    }

    @Override
    public FunctionExpression constructFunction(List<Expression> arguments) {
        return new Count(arguments);
    }

    @Override
    public String generateSql(SQLType type) {
        switch (type) {
        case MySQL:
            StringBuilder sb = new StringBuilder();
            sb.append("COUNT(");
            if (distinct) {
                sb.append("DISTINCT ");
            }
            if (wildcard) {
                sb.append("*");
            } else {
                boolean isFst = true;
                for (Expression expr : arguments) {
                    if (isFst) isFst = false;
                    else sb.append(", ");
                    sb.append(expr.generateSql(type));
                }
            }
            sb.append(')');
            return sb.toString();
        default:
            throw new UnsupportedOperationException("only mysql sql can be generated");
        }
    }
}
